package  com.baomidou.springwind.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.common.util.DateUtil;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.framework.upload.UploadFile;
import com.baomidou.framework.upload.UploadMsg;
import com.baomidou.framework.upload.UploadMultipartRequest;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.App;
import com.baomidou.springwind.entity.AppCategory;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.MemberApp;
import com.baomidou.springwind.entity.MyPermission;
import com.baomidou.springwind.service.IAppCategoryService;
import com.baomidou.springwind.service.IAppService;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.IPermission1Service;
import com.baomidou.springwind.service.IPermissionService;

/**
 *  类目管理控制器首页
 * @author koumiba
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/sysapp/category")
public class CategoryController extends SuperController {
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IPermission1Service permissonService;
	@Autowired
	private IAppService appService;
	@Autowired
	private IAppCategoryService appCategoryService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		
		return "/sysapp/category/index";
	}
	/**
	 * 详情
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detail")
	public String detail(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		String categoryId = request.getParameter("categoryid");
		if(categoryId != null){
			String name = appCategoryService.selectById(Integer.parseInt(categoryId)).getName();
			model.addAttribute("name", name);
		}
		model.addAttribute("categoryid", categoryId);
		return "/sysapp/category/detail";
	}
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/ajax")
	public String ajax(String ac) {
		String display = "";
		if (ac.equals("getList")){
			int from = Integer.parseInt(request.getParameter("from"));
			int to = Integer.parseInt(request.getParameter("to"));
			String search_1 = request.getParameter("search_1");
			EntityWrapper ew = new EntityWrapper<AppCategory>();
			ew.and("issystem=0");
			
			if(search_1 != null && !search_1.equals("")){
				ew.like("name", search_1);
			}
			List<AppCategory> acList = new AppCategory().selectList(ew);
			
			display += acList.size()+"<{|*|}>";
			for(int i=from; (i<=to && i<acList.size()); i++){
				AppCategory acTemp = acList.get(i);
				display += "<tr class='list-bd'>";
				display += "<td style='text-align:left;padding-left:15px'>"+acTemp.getName()+"</td>";
				display += "<td><a href='javascript:openDetailIframe(\"detail.html?categoryid="+acTemp.getTbid()+"\");' class='btn btn-link'>编辑</a><a href='javascript:;' class='btn btn-link do-del' categoryid='"+acTemp.getTbid()+"'>删除</a></td>";
				display += "</tr>";
			}		
		}else if (ac.equals("del")){
			int appCategoryId = Integer.parseInt(request.getParameter("categoryid"));
			EntityWrapper<App> ew = new EntityWrapper<App>();
			ew.and("app_category_id="+appCategoryId);
			List<App> appList = new App().selectList(ew);
			for(App app : appList){
				app.setAppCategoryId((long)0);
				appService.insertOrUpdate(app);
			}
			appCategoryService.deleteById(appCategoryId);
		}
		
		return display;
	}
	
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detailAjax")
	public String detailAjax(String ac) {
		if (ac.equals("edit")){
			String valName = request.getParameter("val_name");
			String id = request.getParameter("id");
			AppCategory entity = new AppCategory();
			entity.setName(valName);
			
			if(id==null || id.equals("")){
				//获取下一个id
				EntityWrapper ew = new EntityWrapper<AppCategory>();
				ew.orderBy("tbid", false);
				int nextAppCategoryId = new AppCategory().selectOne(ew).getTbid().intValue() + 1;
				
				entity.setTbid((long)nextAppCategoryId);
				appCategoryService.insert(entity);
			}else{
				entity = appCategoryService.selectById(Integer.parseInt(id));
				entity.setName(valName);
				appCategoryService.insertOrUpdate(entity);
			}
			Map<String,String> result = new HashMap<String,String>();
			result.put("info", "");
			result.put("status", "y");
			return JSONUtils.toJSONString(result);
		}
		return "";
	}
	
	
	/*************************
	 *    私有方法 
	 *************************/
	
	
	/**
	 * 验证是否为管理员
	 * @return Boolean
	 * koumiba
	 * 2017年3月26日
	 */
	private Boolean checkAdmin(){
		int mid = HoorayosHelper.getMemberId(request);
		EntityWrapper ew = new EntityWrapper(new Member());
		Member m = new Member().selectById(mid);
		return m.getType() == 1 ? true : false;
	}
	/**
	 * <p>
	 * 上传文件存放目录 uploads/shortcut/{yyyy}{mm}{dd}/{time}{rand:6}
	 * </p>
	 */
	private String getSaveDir() {
		StringBuffer filePath = new StringBuffer(session.getServletContext().getRealPath("/"));
		filePath.append(File.separator).append("WEB-INF").append(File.separator).append("static")
		.append(File.separator).append("uploads").append(File.separator).append("shortcut").append(File.separator);
		filePath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(filePath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		
		return file.getPath();
	}
	/**
	 * 获取图片的web访问路径
	 * @return String
	 * koumiba
	 * 2017年4月8日
	 */
	private String getSurlPath(){
		return "/static/uploads/shortcut/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
	}
}
